import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:freedom/entity/restful.dart';
import 'package:freedom/util/customer_dialog.dart';
import 'package:freedom/util/data_type.dart';
import 'package:freedom/util/api_router.dart';
import 'package:freedom/entity/user/verification_mode.dart';
import 'package:freedom/util/http.dart';

typedef _callBack = void Function(VerificationMode data);

void defaultCallback(VerificationMode data) {}

class VerificationWidget extends StatefulWidget {
  final _callBack callBack;
  VerificationWidget({this.callBack = defaultCallback});
  @override
  VerificationWidgetState createState() => VerificationWidgetState();
}

class VerificationWidgetState extends State<VerificationWidget> {
  double _top = 0.0;
  double _left = 0.0;
  final Random _random = Random(DateTime.now().microsecondsSinceEpoch);
  double _verificationCodeWidth = 0;
  double _verificationCodeHeight = 0;
  VerificationMode? _verificationMode;
  Uint8List? _backgrounImage;

  bool? _isSuccess;

  bool? _moveTag;

  Uint8List? _moveImage;

  double? _moveImageHeight;

  bool _loadingError = false;

  @override
  void initState() {
    super.initState();
    _moveTag = false;
    initImage();
  }

  @override
  void dispose() {
    super.dispose();
    _backgrounImage = null;
    _moveImage = null;
    _verificationMode = null;
  }

  void initImage() {
    _moveTag = false;
    _isSuccess = false;
    Http.getInstance().request<Restful>(ApiRouter.verificationCode,
        showLoading: true,
        loadingMsg: "拉取验证码中...",
        showErrorMsg: true,
        contentType: ContentType.json, success: (data) {
      _verificationMode =
          VerificationMode.fromJson(asT<Map<String, dynamic>>(data.body));
      _verificationCodeHeight = 300.h;
      _backgrounImage =
          const Base64Decoder().convert(_verificationMode!.backGroundImage!);
      _moveImage = const Base64Decoder().convert(_verificationMode!.moveImage!);
      _verificationCodeWidth = 300.h * _verificationMode!.scale!;
      _moveImageHeight = _verificationCodeHeight * 0.2;
      // 奖滑块的位置随机生成
      _top =
          _random.nextDouble() * (_verificationCodeHeight - _moveImageHeight!);
      _left =
          _random.nextDouble() * (_verificationCodeWidth - _moveImageHeight!);
      setState(() {});
    }, error: (data) {
      _loadingError = true;
      setState(() {});
    });
  }

  void close({Function? callBack}) {
    _verificationCodeWidth = 0;
    setState(() {});
    Future.delayed(const Duration(milliseconds: 500), () {
      CustomerDialog.closeAllLoading(groupKey: CustomerDialog.verificationCode);
      if (callBack != null) {
        callBack();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_loadingError) {
      CustomerDialog.closeAllLoading(groupKey: CustomerDialog.verificationCode);
    }
    if (_verificationMode == null) {
      return SizedBox(
          width: 400.w,
          child: Dialog(
              elevation: 0.0,
              backgroundColor: Colors.transparent,
              child: SizedBox(
                width: 300.h,
                height: 400.w,
              )));
    }
    return Material(
        color: Colors.transparent,
        child: Stack(
          children: [
            InkWell(
              onTap: () {
                _moveTag = false;
                close();
              },
              child: Container(
                width: double.infinity,
                height: double.infinity,
                color: const Color.fromARGB(186, 0, 0, 0),
              ),
            ),
            Center(
              child: AnimatedContainer(
                height: _verificationCodeHeight,
                width: _verificationCodeWidth,
                decoration: BoxDecoration(
                  color: const Color.fromARGB(71, 255, 255, 255),
                  borderRadius: BorderRadius.circular(10),
                  boxShadow: [
                    BoxShadow(
                      color: const Color.fromARGB(146, 19, 18, 18)
                          .withOpacity(0.5),
                      spreadRadius: 5,
                      blurRadius: 7,
                      offset: const Offset(0, 3), // changes position of shadow
                    ),
                  ],
                ),
                duration: const Duration(milliseconds: 500),
                child: Stack(
                  children: <Widget>[
                    Positioned(
                      child: Container(
                        child: _backgrounImage == null
                            ? const CircularProgressIndicator()
                            : Image.memory(
                                _backgrounImage!,
                                fit: BoxFit.fill,
                                height: double.infinity,
                                width: double.infinity,
                              ),
                      ),
                    ),
                    Align(
                      alignment: const Alignment(0, 0),
                      child: _verificationCodeWidth > 0
                          ? Text(
                              "拖动滑块到阴影处",
                              style: TextStyle(
                                  color: Colors.white, fontSize: 30.sp),
                            )
                          : const SizedBox(),
                    ),
                    _verificationCodeWidth > 0
                        ? Positioned(
                            top: _top,
                            left: _left,
                            child: GestureDetector(
                              child: SizedBox(
                                  width: _moveImageHeight,
                                  height: _moveImageHeight,
                                  child: Stack(children: [
                                    Container(
                                        decoration: BoxDecoration(
                                            boxShadow: [
                                              BoxShadow(
                                                  color: const Color(0xFFFFFFFF)
                                                      .withOpacity(0.5),
                                                  blurRadius: 5.0)
                                            ],
                                            border: Border.all(
                                                color: const Color.fromARGB(
                                                    255, 255, 0, 0),
                                                width: 5.w)),
                                        child: Center(
                                          child: _moveTag!
                                              ? _isSuccess!
                                                  ? Icon(
                                                      Icons.check_circle,
                                                      color: Colors.green,
                                                      size: _moveImageHeight! *
                                                          0.7,
                                                    )
                                                  : Icon(
                                                      Icons.clear,
                                                      color: Colors.red,
                                                      size: _moveImageHeight! *
                                                          0.7,
                                                    )
                                              : Image.memory(
                                                  _moveImage!,
                                                  fit: BoxFit.fill,
                                                  width: _moveImageHeight,
                                                  height: _moveImageHeight,
                                                ),
                                        )),
                                  ])),
                              onPanDown: (DragDownDetails e) {},
                              onPanUpdate: (DragUpdateDetails e) {
                                _left += e.delta.dx;
                                _top += e.delta.dy;
                                if (_left < 0) {
                                  _left = 0;
                                } else if (_left >
                                    _verificationCodeWidth -
                                        _moveImageHeight!) {
                                  _left = _verificationCodeWidth -
                                      _moveImageHeight!;
                                }
                                if (_top < 0) {
                                  _top = 0;
                                } else if (_top >
                                    _verificationCodeHeight -
                                        _moveImageHeight!) {
                                  _top = _verificationCodeHeight -
                                      _moveImageHeight!;
                                }
                                setState(() {});
                              },
                              onPanEnd: (DragEndDetails e) {
                                _verificationMode!.x =
                                    _left / _verificationCodeWidth;
                                _verificationMode!.y =
                                    _top / _verificationCodeHeight;
                                _verificationMode!.backGroundImage = null;
                                _verificationMode!.moveImage = null;
                                Http.getInstance().request<Restful>(
                                    ApiRouter.verificationCheckCode,
                                    type: RequestEnum.POST,
                                    contentType: ContentType.json,
                                    data: _verificationMode!.toJson(),
                                    success: (data) {
                                  setState(() {
                                    _moveTag = true;
                                    _isSuccess = true;
                                  });
                                  Future.delayed(
                                      const Duration(milliseconds: 500), () {
                                    close(callBack: () {
                                      widget.callBack(_verificationMode!);
                                    });
                                  });

                                  /* setState(() {
                                    _moveTag = true;
                                    _isSuccess = true;
                                  });
                                  Future.delayed(
                                      const Duration(milliseconds: 500), () {
                                    CustomerDialog.closeAllLoading(
                                        groupKey:
                                            CustomerDialog.verificationCode);
                                   
                                  }); */
                                }, error: (data) {
                                  setState(() {
                                    _moveTag = true;
                                    _isSuccess = false;
                                  });
                                  Future.delayed(
                                      const Duration(milliseconds: 500), () {
                                    initImage();
                                  });
                                });
                              },
                            ),
                          )
                        : const SizedBox(),
                  ],
                ),
              ),
            )
          ],
        ));
  }
}
